﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace EVEAPI
{
	public abstract class APIbase
	{
		protected string _keyID;
		protected string _vCode;
		protected string _url;
		protected bool _useAuthentication;
		protected XmlDocument _doc;
		protected XmlNode _rowSet;
		protected XmlNode _result;

		protected DateTime? _cachedUntil;

		public string KeyID { get { return _keyID; } }
		public string VCode { get { return _vCode; } }
		public DateTime? CachedUntil { get { return _cachedUntil; } }

		public APIbase(string keyID, string vCode, string url, bool useAuthentication)
		{
			_keyID = keyID;
			_vCode = vCode;
			_url = url;
			_useAuthentication = useAuthentication;
		}

		protected string FormatURL(Hashtable parameters)
		{
			StringBuilder sb = new StringBuilder(_url + "?");
			if (_useAuthentication) sb.AppendFormat("keyID={0}&vCode={1}&", _keyID, _vCode);
			foreach (string key in parameters.Keys) sb.AppendFormat("{0}={1}&", key, parameters[key]);
			sb.Remove(sb.Length - 1, 1);
			return sb.ToString();
		}

		protected bool Refresh(Hashtable parameters)
		{
			bool result = false;
			_doc = new XmlDocument();

			if (_cachedUntil != null && _cachedUntil > DateTime.Now) return true; 

			try
			{
				_doc.Load(FormatURL(parameters));
				_result = _doc["eveapi"]["result"];
				_rowSet = _result["rowset"];

				LoadData();
				result = true;
			}
			catch
			{
				throw;
			}

			return result;
		}

		protected abstract void LoadData();
		public abstract bool Read();

		private void ReadCacheValues()
		{
			DateTime cachedUntil = DateTime.Parse(_doc["eveapi"]["cachedUntil"].InnerText);
			DateTime currentTime = DateTime.Parse(_doc["eveapi"]["currentTime"].InnerText);
			TimeSpan diff = cachedUntil - currentTime;

			_cachedUntil = DateTime.Now + diff;
		}
	}
}
